#ifndef SWANLINK_FINANCE_KEYBOARD_SERVICES_ADAPTOR_KMY3501G_GM_INCLUDE_KMY_ADAPTOR_H
#define SWANLINK_FINANCE_KEYBOARD_SERVICES_ADAPTOR_KMY3501G_GM_INCLUDE_KMY_ADAPTOR_H

#include <string>
#include <pthread.h>
#include <mutex>
#include "kmy305.h"
#include "ikeyboardadaptor.h"

namespace SwanLink {
namespace Finance {
class KMY3501G_GM_Adaptor:public iKeyboard_Adaptor
{
 public:
   KMY3501G_GM_Adaptor();
   virtual ~KMY3501G_GM_Adaptor();
   /*公共接口*/
   virtual int Open(const Transport &tran);
   virtual int Close();
   virtual bool IsOpen();
   virtual int Reset();
   virtual int GetStatus(int module, char *err);

   /*设备功能接口*/
   virtual bool IsSM4Enabled();

   /*
    * 获取密码键盘序列号
    */
   virtual int GetSN(char sn[], int &len);

   /*
    * 计算MAC
    */
   virtual int CalculateMAC(const KeyInfo& key, char plain[], int len, char enc_data[], int &enc_len);

   /*
    * 加密数据
    */
   virtual int EncryptData(const KeyInfo& key, char plain[], int len, char enc_data[], int &len_enc);

   /*
    * 设置PIN的长度限制
    */
   virtual int SetPINLength(int minLen, int maxLen);

   /*
    * 设置明文密文模式
    */
   virtual int SetTextMode(TextMode mode);

   /*
    * 清空文本
    */
   virtual void ClearTextMode();

   /*
    * 加载主密钥
    */
   virtual int LoadMasterKey(KeyID masterKeyID, unsigned char *KeyValue);

   /*
    * 加载用户密钥
    */
   virtual int LoadUserKey(KeyID masterKeyID, userKeyType user_Key_Type, unsigned char *KeyValue);

   /*
    * 更新密钥
    */
   virtual int UpdateMasterKey(KeyID masterKeyID, unsigned char *KeyValue);

   /*
    * 更新用户密钥
    */
   virtual int UpdateUserKey(KeyID masterKeyID, userKeyType user_Key_Type, unsigned char *KeyValue);

   /*
    * 删除用户密钥
    */
   virtual int DeleteUserKey(KeyID masterKeyID, userKeyType user_Key_Type);

   /*
    * 监听
    */
   virtual void ListenForPin(PinListener* listener, int timeout);

    void OnCharProcess(int code, char ch);
    void OnFailed(int code, const std::string &err);
    void OnResult(char *buf, int len);
    void ListenForRead();
    static void* ListenForPinThread(void *arg) {
      KMY3501G_GM_Adaptor *adaptor = static_cast<KMY3501G_GM_Adaptor*>(arg);
      printf("adaptor = %p\n", adaptor);
      adaptor->ListenForRead();
      return NULL;
    }
 private:
    int m_iFd;
    int m_iStatus = -1;
    int MaxData;
    bool flag = false;
    int m_enbale = -1;
    int m_timeout = 3000;
    int m_mode = 1;
    int keybuf_len = 0;
    char keybuf[256] = {0};
    std::mutex  pin_mutex;
    pthread_t  pin_thread_id;
    PinListener* pinListener{nullptr};
};
} // namespace Finance
} // namespace SwanLink

#endif // SWANLINK_FINANCE_KEYBOARD_SERVICES_ADAPTOR_KMY3501G_GM_INCLUDE_KMY_ADAPTOR_H
